<template>
  <div class="modal addModal-modal-lg safe-modal add-modal" id='modal'  @keyup.enter="sendData()"  tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">    
          <h3 class="modal-title" id="myModalLabel">
            <template v-if ="oper=='add'">{{$t('safeplot.addTitle')}} </template>        
            <template v-else-if="oper=='edit'">{{$t('safeplot.editTitle')}}</template>
            <template v-else-if="oper=='del'">{{$t('safeplot.delTitle')}}</template> 
          </h3>
          <span class="close" data-dismiss="modal" aria-hidden="true">&times;</span>
        </div>
        <div class="modal-body">
          <!-- 正在请求 -->
          <div class="result" v-show="result=='ing'">
            <img src="../../../../img/loading.gif" />
            <p style="font-size: 12px;line-height: 20px;">{{$t('safeplot.asking')}}</p>
          </div>
          <!-- 成功 -->
          <div class="result" v-show="result=='ok'" style="line-height:350px">
            <img src="../../../../img/success.png" />
            <span>{{$t('common.successNotice')}}</span>
          </div>
          <!-- table -->
          <div v-show="oper=='del'&&result!='ok' && result!='ing'">
            <p style="line-height: 320px;text-align: center;font-size: 18px;color: #666">
              {{$t('common.delNotice')}}
            </p>
          </div>
          <div class="tbody" v-show="oper!='del'&&result!='ok' && result!='ing'">
            <!-- 协议类型 -->
            <div class="line">
              <div class="tr">
                <label>{{$t('safeplot.plotTableTh2')}}</label>
                <select class="protocol" v-model="protocol_id">
                  <option v-bind:value="item.value" v-for='item in protocal_ar' :key="item.value">{{item.text}}</option>
                </select>
                <span style="color: #495060;margin-left: 10px;">{{$t('safeplot.plotRemark1')}}</span>
              </div>
            </div>
            <!-- IP设置 -->
            <div class="line" style="position: relative;">
              <div class="tr tr-2">
                <label>{{$t('safeplot.plotTableTh3')}}</label>
                <ipSpecial :listener='listener' :special='set_sip.ip' v-on:sendip='gets_ip' :key="'source'"></ipSpecial>
              </div>
              <div class="tr tr-3">
                <label>{{$t('safeplot.plotTableTh4')}}</label>
                <ipSpecial :listener='listener' :special='set_dip.ip' v-on:sendip='getd_ip' :key="'dest'"></ipSpecial>
              </div>
            </div>

            <!-- 端口设置 -->
            <div v-if='this.protocol_id=="6"||this.protocol_id=="17"' class="line port" style="position: relative;">
                <div class="tr">
                    <label>{{$t('safeplot.plotTableTh5')}}</label>
                    <Select v-model="s_port.type" :transfer='transfer' size="small">
                        <Option value="1" :key="0">ANY</Option>
                        <Option value="2" :key="1">{{$t('safeplot.sPort')}}</Option>
                    </Select>
                    <input v-if='s_port.type=="2"' v-model='s_port.val' class="srcprot" type="text" placeholder="8080，80:100，2000"
                      @blur="portTest('.srcprot','protRang')" @focus="isEmpty('.srcprot')" style="margin-left: 5px;">
                </div>
                <div class="tr">
                    <label>{{$t('safeplot.plotTableTh6')}}</label>
                    <Select v-model="d_port.type" :transfer='transfer' size="small">
                        <Option value="1" :key="0">ANY</Option>
                        <Option value="2" :key="1">{{$t('safeplot.sPort')}}</Option>
                    </Select>
                    <input v-if='d_port.type=="2"' v-model='d_port.val' class="desprot" type="text"
                      placeholder="8080，2000，80:100"  @blur="portTest('.desprot','protRang')"
                      @focus="isEmpty('.desprot')" style="margin-left: 5px;">
                </div>
                <p style="color: #495060;">{{$t('safeplot.plotRemark2')}}</p>
            </div>

            <!-- 动作类型，备注 -->
            <div class="line">
              <div class="tr">
                <label>{{$t('safeplot.plotTableTh7')}}</label>
                <Select v-model="select_type" :transfer='transfer' size="small">
                  <Option value="0" :key="1">{{$t('safeplot.allow')}}</Option>
                  <Option value="1" :key="2">{{$t('safeplot.refuse')}}</Option>
                </Select>
              </div>
              <div class="tr">
                <label>{{$t('safeplot.plotTableTh8')}}</label>
                <textarea v-model = "description" class="desc" rows="3" @keyup="TextLength(description)" @blur="TextLength(description)" placeholder="可输入10个字以内的备注"></textarea>
                <span class="notice length_notice">*超出长度限制</span>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <div class="notice">
            <span>*{{errorMsg}}</span>
          </div>
          <button class="button sure-btn button--aylen" @click='sendData()'>{{$t('common.sureBtn')}}</button>
          <button class="button sure-btn button--aylen" data-dismiss="modal">{{$t('common.cancelBtn')}}</button>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
  import ProtocolData from 'libs/ProtocolData'
  import formatTest from 'libs/formatTest'
  import ipSpecial from './ipSpecial'
  export default {
    components:{
      ipSpecial
    },
    props: {
      result: {
        type: String,
        // required: true
      },
      errorMsg: {
        type: String,
        // required: true
      },
      oper: {
        type: String
      },
      selectedItems: {},
      editData: {}
    },
    data() {
      return {
        protocol_id: '0',
        protocal_ar: ProtocolData.data,
        select_type: '0',
        transfer: true,//下拉列表position
        description: '',
        set_sip: {ip: '', status: false, msg: ''},
				set_dip: {ip: '', status: false, msg: ''},
				d_port: {type: "1", val: ''},
        s_port: {type: "1", val: ''},
        listener: 1
      }
    },
    mounted () {
      $('.safe-modal').on('hidden.bs.modal', ()=> {
          this.d_port = {type:"1",val:''}
        	this.s_port = {type:"1",val:''}
      })
    },
    watch: {
      result: function() {
        if (this.result == 'ok') {
          setTimeout(function() {
            $('.addModal-modal-lg').modal('hide')
          }, 500)
        } else if (this.result == 'error') {
          $('.notice').show()
        }
      },
      editData: function() {
        this.listener++
        this.set_sip={ip:'',status:true, msg:''}
        this.set_dip={ip:'',status:true, msg:''}
        this.select_type='0'
        this.protocol_id='0'
        this.description=''
        if (this.editData.protocol_id) {
          this.protocol_id = this.editData.protocol_id?ProtocolData.key(this.editData.protocol_id):'138'
					this.select_type = this.editData.action==this.$t('safeplot.refuse')?'1':'0'
					this.set_dip.ip = this.editData.dst_ip 
					this.set_sip.ip = this.editData.src_ip
					if (this.editData.d_port) {
							this.d_port.type ='2'
					} else {
							this.d_port.type ='1'
					}
					if (this.editData.s_port) {
							this.s_port.type ='2'
					} else {
							this.s_port.type ='1'
					}
					this.d_port.val=this.editData.d_port
          this.s_port.val=this.editData.s_port
          this.description=this.editData.description
        }
      }
    },
    methods: {
      gets_ip(val) {
        this.set_sip = val
        if (val.status) {
          this.s_ip = val.ip
        }
      },
      getd_ip(val) {
        this.set_dip = val
        if (val.status) {
          this.d_ip = val.ip
        }
      },
      sendData() {
        if (this.oper === 'del') {
          this.$emit('delEvent',{'1': this.selectedItems.join(',')})
          return
        }
        if (!(this.set_sip.status && this.set_dip.status)) {
            return
        }

        let sip = this.set_sip.ip       
        let dip = this.set_dip.ip

				let descValid = this.TextLength(this.description)
				if (!descValid) {
					return
				}

				let sportValid = false
				let dportValid = false

				if (this.protocol_id === '6' || this.protocol_id === '17') {
						if (this.s_port.type === '1') {
								sportValid = true
						} else {
								sportValid = this.portTest('.srcprot', 'protRang')
						}
						if (this.d_port.type === '1') {
								dportValid = true
						} else {
								dportValid = this.portTest('.desprot', 'protRang')
						}
				} else {
						sportValid = true
						dportValid = true
						$('.desprot').val('')
						$('.srcprot').val('')
				}

				if (!sportValid || !dportValid) {
					return
				}

        let params = {
          protocol_id: this.protocol_id,
          src: this.set_sip.ip,
					dst: this.set_dip.ip,       
					s_port: this.s_port.type === '1' ? '' : $('.srcprot').val(),					
					d_port: this.d_port.type === '1' ? '' : $('.desprot').val(),
          action: this.select_type,
          description: this.description
        }
        let sendStr = ''
        switch (this.oper) {
          case 'edit':
             sendStr = `${this.editData.id}|${this.protocol_id}|${this.set_sip.ip}|${this.set_dip.ip}|`
             + `${this.s_port.type === '1' ? '' : $('.srcprot').val()}|${this.d_port.type === '1' ? '' : $('.desprot').val()}`
             + `|${this.select_type}|${this.description}`
             this.$emit('editEvent',{'1': sendStr})
            break;
          default:
            sendStr = `${this.protocol_id}|${this.set_sip.ip}|${this.set_dip.ip}|`
             + `${this.s_port.type === '1' ? '' : $('.srcprot').val()}|${this.d_port.type === '1' ? '' : $('.desprot').val()}`
             + `|${this.select_type}|${this.description}`
             this.$emit('addEvent',{'1': sendStr})
            break;
        }
      },
      TextLength(desc) {
        if (desc.length>10) {
          $('.length_notice').show()
          return false
        } else {
          $('.length_notice').hide()
          return true
        }
			},
			portTest: function(ele, reg) {
				if ($(ele).val() === '') {
					$(ele).css('border', '1px solid #b63039')
					$(ele).addClass('animated shake')
					setTimeout(function() {
						$(ele).removeClass('animated shake')
					}, 200)							
					format = false
					return false
				}
				let formatTest = this.testVal(ele, reg,false)			
				if (formatTest) {
					let format = true
					let portVal = $(ele).val()
					let valArr = portVal.split(",")
					for(let i = 0; i < valArr.length; i++) {
						if (valArr[i].indexOf(':')) {
							let portArr = valArr[i].split(":")							
							if (Number(portArr[0]) > Number(portArr[1])) {
								$(ele).css('border', '1px solid #b63039')
								$(ele).addClass('animated shake')
								setTimeout(function() {
									$(ele).removeClass('animated shake')
								}, 200)							
								format = false
								return false
							}
						}
					}
          return format
				} else {
				  return formatTest
				}
			},
      testVal: function(ele, reg) {
        let val = $(ele).val().split('/')[0]
        if (val.split('-').length>0) {
          for(let i=0;i<val.split('-').length;i++) {
            if (val.split('-')[i].trim()=='0.0.0.0') {
                $(ele).css('border', '1px solid #b63039')
                $(ele).addClass('animated shake')
                setTimeout(function() {
                  $(ele).removeClass('animated shake')
                }, 200)
                return false
            }
          }
        }
        if (val=='0.0.0.0') {
          $(ele).css('border', '1px solid #b63039')
          $(ele).addClass('animated shake')
          setTimeout(function() {
            $(ele).removeClass('animated shake')
          }, 200)
          return false
        }
        let test = new formatTest(ele, reg, false)
        return test.testFormat()
      },
      isEmpty: function(ele) {
        let test = new formatTest(ele)
        test.isEmpty()
        $(ele).css('border', '1px solid rgb(232, 232, 232)')
        $('.notice').hide()
      }
    }
  }
</script>

<style lang="less" scoped>
.notice{
  margin-left: 10px;
  color: #ff3300;  
  display: none;
}
</style>
